/**
 * Todo的intent 
 */

import xs from 'xstream';
import { DOMSource } from '@cycle/dom';
import { TodoAction } from '../../types';
import { ENTER_KEY, ESC_KEY } from '../../../util';

export default function intent(DOM : DOMSource) : TodoAction {
    // .eidt: 编辑框
    
    // 编辑框按回车（输入不为空）
    const editEnterEvent$ = DOM
        .select('.edit').events('keyup')
        .filter(ev => {
            const event = <KeyboardEvent>ev;
            const value = (<HTMLInputElement>ev.target).value;
            return event.keyCode === ENTER_KEY && !!value;
        });
    // 编辑框按回车（输入为空）
    const editDeleteEvent$ = DOM
        .select('.edit').events('keyup')
        .filter(ev => {
            const event = <KeyboardEvent>ev;
            const value = (<HTMLInputElement>ev.target).value;
            return event.keyCode === ENTER_KEY && !value;
        });
    // 点击删除按钮
    const destoryClickEvent$ = DOM
        .select('.destroy').events('click')
    // 光标离开编辑框
    const editBlurEvent$ = DOM.select('.edit').events('blur', {
        useCapture: true
    });

    return {
        startEdit$: DOM
            .select('label').events('dblclick')
            .mapTo(null),

        doneEdit$: xs.merge(editEnterEvent$, editBlurEvent$)
            .map(ev => {
                const input = ev.target as HTMLInputElement;
                return input.value;
            }),

        cancelEdit$: DOM
            .select('.edit').events('keyup')
            .filter(ev => {
                return (<KeyboardEvent>ev).keyCode === ESC_KEY;
            })
            .mapTo(null),

        toggle$: DOM
            .select('.toggle').events('change')
            .map(ev => (<HTMLInputElement>ev.target).checked),

        destroy$: xs.merge(editDeleteEvent$, destoryClickEvent$)
            .mapTo(null),
    }
}